// PageController.java
package com.tzkyzj.tiremanager.contorller;

import com.tzkyzj.tiremanager.entity.Tire;
import com.tzkyzj.tiremanager.entity.TirePhoto;
import com.tzkyzj.tiremanager.entity.User;
import com.tzkyzj.tiremanager.repository.TirePhotoRepository;
import com.tzkyzj.tiremanager.service.TireService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

@Controller
public class PageController {

    // 在 PageController 中添加这些依赖
    private final TireService tireService;
    private final TirePhotoRepository tirePhotoRepository;

    public PageController(TireService tireService, TirePhotoRepository tirePhotoRepository) {
        this.tireService = tireService;
        this.tirePhotoRepository = tirePhotoRepository;
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request) {
        // 如果用户已经登录，直接跳转到首页
        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute("currentUser");
            if (user != null) {
                return "redirect:/dashboard";
            }
        }
        return "login";
    }

    @GetMapping("/user-management")
    public String userManagement() {
        return "user-management";
    }

    @GetMapping("/tire-list")
    public String tireList() {
        return "tire-list";
    }

    @GetMapping("/dashboard")
    public String dashboard() {
        return "tire-list"; // 重定向到轮胎列表页面作为主页
    }

    @GetMapping("/")
    public String index() {
        return "redirect:/tire-list";
    }

    // 其他页面跳转方法...
    @GetMapping("/api/tires")
    public String tires() {
        return "tire-list";
    }

    @GetMapping("/api/tires/batch-add")
    public String batchAddTire() {
        return "tire-batch-form";
    }

    @GetMapping("/api/tires/usage")
    public String tireUsage(Model model) {
        model.addAttribute("transportCompanies", tireService.getAllTransportCompanies());
        return "usage-query";
    }

    // 添加 POST 方法处理使用记录查询
    @PostMapping("/api/tires/usage")
    public String getUsageRecord(@RequestParam String tireNumber, Model model) {
        TireService.TireUsageStats stats = tireService.getTireUsageStats(tireNumber);
        model.addAttribute("stats", stats);
        model.addAttribute("transportCompanies", tireService.getAllTransportCompanies());
        return "usage-result";
    }

    @GetMapping("/api/tires/visualization")
    public String tireVisualization() {
        return "tire-visualization";
    }

    @GetMapping("/api/tires/statistics")
    public String tireStatistics() {
        return "tire-statistics";
    }

    @GetMapping("/api/tires/settlement")
    public String tireSettlement() {
        return "settlement";
    }

    @GetMapping("/api/tires/cost-statistics")
    public String tireCostStatistics() {
        return "cost-statistics";
    }

    // 轮胎详情和编辑页面
    @GetMapping("/api/tires/{id}")
    public String tireDetail(@PathVariable Long id, Model model) {
        // 获取轮胎详情
        Tire tire = tireService.getTireById(id).orElse(null);
        if (tire == null) {
            return "redirect:/api/tires"; // 或者返回错误页面
        }
        model.addAttribute("tire", tire);
        model.addAttribute("tireId", id);

        // 获取普通照片 (photo_type = 'GENERAL')
        List<TirePhoto> generalPhotos = tirePhotoRepository.findByTireIdAndPhotoType(id, "GENERAL");
        model.addAttribute("generalPhotos", generalPhotos);
        System.out.println("普通照片数量: " + (generalPhotos != null ? generalPhotos.size() : 0));

        // 获取修补照片 (photo_type = 'REPAIR')
        List<TirePhoto> repairPhotos = tirePhotoRepository.findByTireIdAndPhotoType(id, "REPAIR");
        model.addAttribute("repairPhotos", repairPhotos);
        System.out.println("修补照片数量: " + (repairPhotos != null ? repairPhotos.size() : 0));

        // 获取调胎照片 (photo_type = 'SWAP' 或 'SCRAP')
        List<TirePhoto> swapPhotos = tirePhotoRepository.findByTireIdAndPhotoTypeIn(id, Arrays.asList("SWAP", "SCRAP"));
        model.addAttribute("swapPhotos", swapPhotos);
        System.out.println("调胎照片数量: " + (swapPhotos != null ? swapPhotos.size() : 0));

        // 计算记录数量
        int repairRecordCount = tire.getRepairRecords() != null ?
                tire.getRepairRecords().split("\n").length : 0;
        int swapRecordCount = tire.getSwapRecords() != null ?
                tire.getSwapRecords().split("\n").length : 0;

        model.addAttribute("repairRecordCount", repairRecordCount);
        model.addAttribute("swapRecordCount", swapRecordCount);

        return "tire-detail";
    }

    @GetMapping("/api/tires/{id}/edit")
    public String showEditTireForm(@PathVariable("id") Long id, Model model) {
        try {
            Tire tire = tireService.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("无效的轮胎ID: " + id));
            model.addAttribute("tire", tire);
            return "edit-tire"; // 返回修改页面视图
        } catch (Exception e) {
            model.addAttribute("error", "加载轮胎信息失败: " + e.getMessage());
            return "redirect:/api/tires";
        }
    }

    @GetMapping("/api/tires/{id}/repair")
    public String showRepairForm(@PathVariable Long id, Model model) {
        Tire tire = tireService.getTireById(id).orElse(null);
        if (tire == null) {
            return "redirect:/tires";
        }
        model.addAttribute("tire", tire);
        return "repair-form";
    }

    // 显示调胎记录表单
    @GetMapping("/api/tires/{id}/swap")
    public String showSwapForm(@PathVariable Long id, Model model) {
        Tire tire = tireService.getTireById(id).orElse(null);
        if (tire == null) {
            return "redirect:/tires";
        }
        model.addAttribute("tire", tire);
        model.addAttribute("currentDate", LocalDate.now());
        model.addAttribute("axleOptions", getAxleOptions());
        model.addAttribute("positionOptions", getPositionOptions());
        model.addAttribute("transportCompanies", tireService.getAllTransportCompanies());
        return "swap-form";
    }

    // 获取轴选项
    private List<Integer> getAxleOptions() {
        return Arrays.asList(1, 2, 3, 4, 5, 6);
    }
    // 获取轮胎位置选项
    private List<String> getPositionOptions() {
        return Arrays.asList("左内", "左外", "右内", "右外");
    }
}